<?php
namespace Core;
defined('ENV') || exit('illegal Access! @110');
class Response
{
	const STATUS_SUCCESS = 1;
	const STATUS_FAILURE = -1;
    
    public function __construct()
    {}
    
    /**
     * 用于输出固定结构的json数据
     * @param int $code
     * @param string $msg
     * @param string|array $data
     */
	public static function json($code, $msg, $data='')
	{
        header("Content-type: application/json; charset=utf-8");
        // json_encode(data, option); option int $option 编码选项 (例如: JSON_UNESCAPED_UNICODE 汉字原样输出, 不再编码为uXXXX php5.4)
		$info = array( 'code' => $code, 'msg' => $msg, 'data' => $data, 'request_time' => date('Y-m-d H:i:s', REQUEST_TIME), 'response_time' => date('Y-m-d H:i:s') );
        $json = json_encode($info, JSON_UNESCAPED_UNICODE);
        exit($json);
	}
    
	/**
	 * desc 成功时, 返回json数据
	 * @param string $msg
	 * @param array|string $rs
	 * @param null $code 默认为 1
	 */
	public static function success($rs = array(), $msg = 'success', $code = NULL)
	{
        $code = isset($code) ? $code : self::STATUS_SUCCESS;
        self::json($code, $msg, $rs);
	}

	/**
	 * desc 失败时, 返回json数据
	 * @param string $msg
	 * @param array $rs
     * @param null $code 默认为-1
	 */
	public static function error($msg='', $rs = array(), $code = NULL)
	{
        $code = isset($code) ? $code : self::STATUS_FAILURE;
        self::json($code, $msg, $rs);
	}

    /**
     * 接收对象参数并返回json
     * @param Libs\Notice $obj
     */
	public static function obj($obj)
	{
		header("Content-type: application/json; charset=utf-8");
        $obj->request_time = date('Y-m-d H:i:s', REQUEST_TIME);
        $obj->response_time = date('Y-m-d H:i:s');
        exit(json_encode($obj, JSON_UNESCAPED_UNICODE));
	}
    
    /**
     * 返回任意结构的json
     * @param mixed $data
     * @param
     */
    public static function jsonReturn($data, $option = NULL)
    {
        header("Content-type: application/json; charset=utf-8");
        exit(json_encode($data, $option));
    }

	//提示信息，不跳转
	public static function notify($msg)
	{
		header("Content-type: text/html; charset=utf-8");
		exit($msg);
	}

	//提示信息，并跳转到其他页面
	public static function redirect($msg, $url, $second = 2)
	{
		header("Content-type: text/html; charset=utf-8");
		header("refresh:{$second};url={$url}");
		$str = "<!DOCTYPE html><html lang='zh'><head><meta charset='UTF-8'><title>页面即将跳转</title><meta name='viewport' content='maximum-scale=1.0,minimum-scale=1.0,user-scalable=0,width=device-width,initial-scale=1.0'/></head><body><div style='width: 100vw; height: 100vh; margin-top: 5rem; text-align: center; font-size: 2rem'>{$msg}</div></body></html>";
		exit($str);
	}
 
	//直接跳转到其他页面
    public static function jump($url)
    {
        header("Content-type: text/html; charset=utf-8");
        header("refresh:1;url={$url}");
        exit;
    }
	
}
